import 'package:bot_toast/bot_toast.dart';
import 'package:cave_flutter/model/base_source_model.dart';
import 'package:cave_flutter/model/image_model.dart';
import 'package:cave_flutter/model/other_user_model.dart';
import 'package:cave_flutter/model/user_model.dart';
import 'package:cave_flutter/model/whl_user_info_model.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/task_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:get/get.dart';

import '../../../network/whl_api.dart';
import '../../../utils/whl_avatar_utils.dart';
import '../../../utils/whl_dialog_util.dart';
import '../../../utils/whl_toast_utils.dart';
import '../../whl_login/complete_user_info/selected_sex/selected_sex_logic.dart';

class Edit_userinfoLogic extends GetxController {
  List<BaseItemSectionModel> listData = [];
  OtherUserModel otherUserModel = OtherUserModel();
  double progress = 0;
  String? filePath;
  String? avatarUrl;
  List<SexModel> sexList = [
    // '男生',
    // '女生',
    // '中性',
    // '跨性别男性',
    // '跨性别女性',
    // '偏男两性人',
    // '偏女两性人',
    // '无性别',
  ];
  List<SexModel> educationList = [
    // '大专及以下',
    // '本科',
    // '硕士',
    // '博士',
  ];

  List<SexModel> sexOrg = [
    // '主流',
    // 'T',
    // 'F',
    // 'H',
    // 'BTM',
    // 'TP',
    // 'VERS',
    // '双性恋',
    // '泛性恋',
    // '智性恋',
    // '颜性恋',
    // '性单恋',
    // '半性恋',
    // '无性恋',
    // 'Four Love'
  ];

  List<SexModel> funRole = [
    // 'Sado', 'Maso', 'Dom', 'Sub', 'Switch', 'CD'
  ];

  List<SexModel> qgztList = [];

  List<SexModel> friendList = [];

  UserModel? userModel;

  BaseItemModel? editingModel;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    // setupAllData();
    getUserConfig();
    getUserDetail();
  }

  getUserConfig() {
    WhlApi.myUserInformation.get({}, withLoading: true).then((value) {
      if (value.isSuccess()) {
        otherUserModel = OtherUserModel.fromJson(value.data);
        setupAllData();
      }
    });
  }

  getUserDetail() {
    WhlApi.getPersonDetail.get(
        {"accountId": WhlUserUtils.getUserInfo().accountId},
        withLoading: true).then((value) {
      if (value.isSuccess()) {
        userModel = UserModel.fromJson(value.data);
        setupAllData();
      }
    });
  }

  saveUserInfo(BaseItemModel model) {
    Map<String, dynamic> param = {model.requestKey ?? "": model.requestValue};
    WhlApi.saveUserBaseInfo.post(param, withLoading: true).then((value) {
      if (value.isSuccess()) {
        MyToast.show("保存成功");
        WhlUserInfoModel infoModel = WhlUserUtils.getUserInfo();
        infoModel.gender = model.requestValue.toString();
        WhlUserUtils.saveUserInfo(infoModel);
      }
    });
  }

  saveAvatar(String url, BaseItemSectionModel sectionModel) {
    Map<String, dynamic> param = {"avatar": url};
    WhlApi.saveUserBaseInfo.post(param).then((value) {
      if (value.isSuccess()) {
        MyToast.show("头像设置成功");
        WhlUserInfoModel infoModel = WhlUserUtils.getUserInfo();
        infoModel.avatar = url;
        sectionModel.value = url;
        WhlUserUtils.saveUserInfo(infoModel);
        update();
      }
      BotToast.closeAllLoading();
    });
  }

  saveUserConfig({BaseItemModel? model, Map<String, dynamic>? otherParam}) {
    Map<String, dynamic> param = {model?.requestKey ?? "": model?.requestValue};
    if (otherParam != null) {
      param = otherParam;
    }
    WhlApi.saveUserInformation.post(param, withLoading: true).then((value) {
      if (value.isSuccess()) {
        MyToast.show("保存成功");
        calcProgress();
      }
    });
  }

  selectPhoto(BaseItemSectionModel sectionModel) {
    AvatarUtils.onChoosePhoto(Get.context!, onSelectEnd: (path) {
      avatarUrl = null;
      filePath = path;
      // update();
      BotToast.showLoading();
    }, onSuccess: (url) {
      avatarUrl = url;
      if (url.isEmpty) {
        filePath = null;
      }
      saveAvatar(url, sectionModel);
      calcProgress();
    });
    // update();
  }

  getSexData() {
    WhlApi.getGenderList.get({"type": 1}).then((value) {
      if (value.isSuccess()) {
        List data = value.data;
        List<SexModel> sexData = [];
        sexData = data.map((e) {
          SexModel model = SexModel(name: e["lable"], value: e["id"]);
          return model;
        }).toList();
        sexList.addAll(sexData);
        WhlApi.getGenderList.get({"type": 2}).then((value) {
          if (value.isSuccess()) {
            List data = value.data;
            List<SexModel> sexData = [];
            sexData = data.map((e) {
              SexModel model = SexModel(name: e["lable"], value: e["id"]);
              return model;
            }).toList();
            sexList.addAll(sexData);
            showSelectGenderView();
            update();
          }
        });
      }
    });
  }

  getSexQXData() {
    WhlApi.getSexQXList.get({}).then((value) {
      List data = value.data;
      for (var e in data) {
        SexModel model =
            SexModel(name: e["lable"], value: e["id"], describe: e["note"]);
        List child = e["child"] ?? [];
        if (child.isNotEmpty) {
          List<SexModel> chiData = child.map((subE) {
            SexModel subModel = SexModel(
                name: subE["lable"], value: subE["id"], describe: subE["note"]);
            return subModel;
          }).toList();
          sexOrg.addAll(chiData);
        } else {
          sexOrg.add(model);
        }
      }
      showSelectSexualOrientationView();
      update();
    });
  }

  getQQJSData() {
    WhlApi.getQQJSList.get({}).then((value) {
      List data = value.data;
      funRole = data.map((e) {
        SexModel model =
            SexModel(name: e["lable"], value: e["id"], describe: e["note"]);
        return model;
      }).toList();
      showSelectFunRoleView();
      update();
    });
  }

  getEducationData() {
    WhlApi.getEducationList.get({}).then((value) {
      List data = value.data;
      educationList = data.map((e) {
        SexModel model =
            SexModel(name: e["lable"], value: e["id"], describe: e["note"]);
        return model;
      }).toList();
      showSelectEducationView();
      update();
    });
  }

  getFriendData() {
    WhlApi.getFriendMDList.get({}).then((value) {
      List data = value.data;
      friendList = data.map((e) {
        SexModel model =
            SexModel(name: e["lable"], value: e["id"], describe: e["note"]);
        return model;
      }).toList();
      showSelectFriendView();
      update();
    });
  }

  getQGZTData() {
    WhlApi.getQGZTList.get({}).then((value) {
      List data = value.data;
      qgztList = data.map((e) {
        SexModel model =
            SexModel(name: e["lable"], value: e["id"], describe: e["note"]);
        return model;
      }).toList();
      showSelectQGZTView();
      update();
    });
  }

  setupAllData() {
    listData.clear();
    print(userModel?.soulTagList);
    listData.add(setupAvatarModel());
    listData.add(setupPhotoModel());
    listData.add(setupMineDescModel());
    listData.add(setupUserInfoModel());
    listData.add(setupTagModel());
    calcProgress();
  }

  void calcProgress() {
    double resultProgree = 0;
    if (WhlUserUtils.getAvatar().isNotEmpty) {
      resultProgree += 0.15;
    }
    if (otherUserModel.introduction != null &&
        otherUserModel.introduction!.isNotEmpty) {
      resultProgree += 0.3;
    }
    if ((otherUserModel.uploadUserAlbumBO ?? []).isNotEmpty) {
      resultProgree += 0.15;
    }
    List<String> emptyKey = [];
    BaseItemSectionModel? userInfoModel =
        listData.firstWhereOrNull((e) => e.title == '个人资料');
    userInfoModel?.itemDatas?.forEach((element) {
      if (element.value == null || element.value.isEmpty) {
        emptyKey.add(element.emptyKey);
      }
    });
    if (userInfoModel != null && emptyKey.isEmpty) {
      resultProgree += 0.3;
    }
    if ((userModel?.soulTagList ?? []).isNotEmpty) {
      resultProgree += 0.1;
    }
    if (resultProgree >= 0.99) {
      TaskUtils.complateTask(1, type: 1);
    }
    progress = resultProgree;
    update();
  }

  setupAvatarModel() {
    BaseItemSectionModel sectionModel = BaseItemSectionModel(
        title: "头像",
        modelType: BaseModelTypeENUM.MODELTYPE_Avatar,
        value: WhlUserUtils.getAvatar(),
        otherDatas: 0.15);
    return sectionModel;
  }

  setupPhotoModel() {
    BaseItemSectionModel sectionModel =
        BaseItemSectionModel(title: "我的相册", otherDatas: 0.15, otherValue: "");

    BaseItemModel photoModel = BaseItemModel(
        title: "",
        itemType: BaseItemTypeENUM.ENUM_AddCell,
        datas: otherUserModel.uploadUserAlbumBO ?? []);
    sectionModel.itemDatas!.add(photoModel);
    return sectionModel;
  }

  setupMineDescModel() {
    BaseItemSectionModel sectionModel = BaseItemSectionModel(
        title: "个人介绍",
        otherDatas: 0.3,
        otherValue: "编辑",
        // value: configData["introduction"],
        modelType: BaseModelTypeENUM.MODELTYPE_Title);

    BaseItemModel descModel = BaseItemModel(
        title: "",
        value: otherUserModel.introduction,
        itemType: BaseItemTypeENUM.ENUM_MoreInputCell,
        hitString: "有研究显示自我介绍不低于20个字可以获得更多关注...");
    sectionModel.itemDatas!.add(descModel);
    return sectionModel;
  }

  BaseItemSectionModel setupUserInfoModel() {
    WhlUserInfoModel userModel = WhlUserUtils.getUserInfo();
    BaseItemSectionModel sectionModel =
        BaseItemSectionModel(title: "个人资料", otherDatas: 0.3, otherValue: "");

    BaseItemModel nickModel = BaseItemModel(
      title: "昵称",
      itemType: BaseItemTypeENUM.ENUM_SelectCell,
      requestKey: "nickName",
      modelType: BaseModelTypeENUM.MODELTYPE_NameModel,
      value: userModel.nickname,
    );

    BaseItemModel sexModel = BaseItemModel(
      title: "性别",
      itemType: BaseItemTypeENUM.ENUM_SelectCell,
      requestKey: "gender",
      value: userModel.gender,
      modelType: BaseModelTypeENUM.MODELTYPE_genderModel,
    );
    sexModel.value = otherUserModel.gender?.lable;

    BaseItemModel hModel = BaseItemModel(
        title: "身高",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "height",
        value: otherUserModel.height ?? "");

    BaseItemModel wModel = BaseItemModel(
        title: "体重",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "weight",
        value: otherUserModel.weight ?? "");

    BaseItemModel schoolModel = BaseItemModel(
        title: "毕业院校",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "school",
        value: otherUserModel.school ?? "");

    BaseItemModel xlModel = BaseItemModel(
        title: "最高学历",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "education",
        modelType: BaseModelTypeENUM.MODELTYPE_educationModel);
    xlModel.value = otherUserModel.education?.lable;

    BaseItemModel hyModel = BaseItemModel(
        title: "行业/职业",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "worker",
        value: otherUserModel.worker ?? "");

    BaseItemModel yxModel = BaseItemModel(
        title: "月薪",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "monthlyPay",
        value: otherUserModel.monthlyPay ?? "");

    BaseItemModel xzModel = BaseItemModel(
        title: "星座",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "constellation",
        value: otherUserModel.constellation ?? "");

    BaseItemModel qgztModel = BaseItemModel(
      title: "情感状态",
      itemType: BaseItemTypeENUM.ENUM_SelectCell,
      requestKey: "emotionalState",
      modelType: BaseModelTypeENUM.MODELTYPE_qgzt,
      value: otherUserModel.emotionalState?.lable ?? "",
    );

    BaseItemModel jymdModel = BaseItemModel(
        title: "交友目的",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "addFriendTarget",
        modelType: BaseModelTypeENUM.MODELTYPE_friend,
        value: otherUserModel.addFriendTarget?.first?.lable);

    BaseItemModel qgqxModel = BaseItemModel(
        title: "情感取向",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "sexual_orientation",
        modelType: BaseModelTypeENUM.MODELTYPE_sexualOrientation);

    qgqxModel.value = otherUserModel.sexualOrientation?.lable;

    BaseItemModel qqjsModel = BaseItemModel(
        title: "情趣角色",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "fun_role",
        modelType: BaseModelTypeENUM.MODELTYPE_funRoleModel);
    qqjsModel.value = otherUserModel.funRole?.lable;

    BaseItemModel aqcModel = BaseItemModel(
        title: "安全词",
        itemType: BaseItemTypeENUM.ENUM_SelectCell,
        requestKey: "secureDesc",
        value: otherUserModel.secureDesc ?? "");

    sectionModel.itemDatas!.add(nickModel);
    sectionModel.itemDatas!.add(sexModel);
    sectionModel.itemDatas!.add(hModel);
    sectionModel.itemDatas!.add(wModel);
    sectionModel.itemDatas!.add(schoolModel);
    sectionModel.itemDatas!.add(xlModel);
    sectionModel.itemDatas!.add(hyModel);
    sectionModel.itemDatas!.add(yxModel);
    sectionModel.itemDatas!.add(xzModel);
    sectionModel.itemDatas!.add(qgztModel);
    sectionModel.itemDatas!.add(jymdModel);
    sectionModel.itemDatas!.add(qgqxModel);
    sectionModel.itemDatas!.add(qqjsModel);
    if (userModel.funRole == '1' ||
        userModel.funRole == '3' ||
        userModel.funRole == '4') {
      sectionModel.itemDatas!.add(aqcModel);
    }
    return sectionModel;
  }

  setupTagModel() {
    BaseItemSectionModel sectionModel = BaseItemSectionModel(
      title: "灵魂标签",
      otherDatas: 0.1,
      otherValue: "编辑",
      modelType: BaseModelTypeENUM.MODELTYPE_Tag,
      value: userModel?.soulTagList?.join(','),
    );

    BaseItemModel tagModel = BaseItemModel(
      title: "",
      itemType: BaseItemTypeENUM.ENUM_SelectTypeCell,
      datas: userModel?.soulTagList,
    );
    sectionModel.itemDatas!.add(tagModel);
    print("object1111");
    print(userModel?.soulTagList);
    return sectionModel;
  }

  Future<void> toSectionEditPage(BaseItemSectionModel sectionModel) async {
    if (sectionModel.modelType == BaseModelTypeENUM.MODELTYPE_Title) {
      BaseItemModel? itemModel = sectionModel.itemDatas?.first;
      var result =
          await Get.toNamed(Routes.editDesc, arguments: itemModel?.value);
      if (result != null) {
        itemModel?.value = result;
        otherUserModel.introduction = result;
        calcProgress();
      }
    } else if (sectionModel.modelType == BaseModelTypeENUM.MODELTYPE_Tag) {
      var result = await Get.toNamed(Routes.improveInformation,
          arguments: {"isSetter": true});
      if (result != null) {
        getUserDetail();
      }
    }
  }

  Future<void> toEditItemPage(BaseItemModel model) async {
    var a = await Get.toNamed(Routes.editUserItem, arguments: {"model": model});
    if (a != null) {
      update();
    }
  }

  showSelectGenderView() {
    WhlDialogUtil.showSexModelBottomSheet(Get.context!, sexList,
        callBack: (SexModel selectModel) {
      editingModel?.value = selectModel.name;
      editingModel?.requestValue = selectModel.value;
      saveUserInfo(editingModel!);
      update();
    });
  }

  showSelectEducationView() {
    WhlDialogUtil.showSexModelBottomSheet(Get.context!, educationList,
        callBack: (SexModel selectModel) {
      editingModel?.value = selectModel.name;
      editingModel?.requestValue = selectModel.value;
      saveUserConfig(model: editingModel);
      // update();
    });
  }

  showSelectFunRoleView() {
    WhlDialogUtil.showSexModelBottomSheet(Get.context!, funRole,
        callBack: (SexModel selectModel) {
      editingModel?.value = selectModel.name;
      editingModel?.requestValue = selectModel.value;
      saveUserConfig(model: editingModel);
      // update();
    });
  }

  showSelectSexualOrientationView() {
    WhlDialogUtil.showSexModelBottomSheet(Get.context!, sexOrg,
        callBack: (SexModel selectModel) {
      editingModel?.value = selectModel.name;
      editingModel?.requestValue = selectModel.value;
      saveUserConfig(model: editingModel);
      // update();
    });
  }

  showSelectQGZTView() {
    WhlDialogUtil.showSexModelBottomSheet(Get.context!, qgztList,
        callBack: (SexModel selectModel) {
      editingModel?.value = selectModel.name;
      editingModel?.requestValue = selectModel.value;
      saveUserConfig(model: editingModel);
      // update();
    });
  }

  showSelectFriendView() {
    WhlDialogUtil.showSexModelBottomSheet(Get.context!, friendList,
        callBack: (SexModel selectModel) {
      editingModel?.value = selectModel.name;
      editingModel?.requestValue = selectModel.value;
      saveUserConfig(otherParam: {
        editingModel?.requestKey ?? "": [editingModel?.requestValue ?? ""]
      });
      // update();
    });
  }

  void selectViewAction(BaseItemModel model) {
    editingModel = model;
    if (model.modelType == BaseModelTypeENUM.MODELTYPE_genderModel) {
      if (sexList.isEmpty) {
        getSexData();
      } else {
        showSelectGenderView();
      }
    } else if (model.modelType == BaseModelTypeENUM.MODELTYPE_educationModel) {
      if (educationList.isEmpty) {
        getEducationData();
      } else {
        showSelectEducationView();
      }
    } else if (model.modelType == BaseModelTypeENUM.MODELTYPE_funRoleModel) {
      if (funRole.isEmpty) {
        getQQJSData();
      } else {
        showSelectFunRoleView();
      }
    } else if (model.modelType ==
        BaseModelTypeENUM.MODELTYPE_sexualOrientation) {
      if (sexOrg.isEmpty) {
        getSexQXData();
      } else {
        showSelectSexualOrientationView();
      }
    } else if (model.modelType == BaseModelTypeENUM.MODELTYPE_qgzt) {
      if (qgztList.isEmpty) {
        getQGZTData();
      } else {
        showSelectQGZTView();
      }
    } else if (model.modelType == BaseModelTypeENUM.MODELTYPE_friend) {
      if (friendList.isEmpty) {
        getFriendData();
      } else {
        showSelectFriendView();
      }
    } else {
      toEditItemPage(model);
    }
  }

  void bindPhoto(List value) {
    List allUrls = [];
    for (ImageModel element in value) {
      if (element.imageStatus == 1) {
        allUrls.add(element.imageUrl);
      }
    }
    // if (allUrls.isNotEmpty) {
    saveUserConfig(otherParam: {
      "uploadUserAlbumBO": {"urls": allUrls}
    });
    // }
  }
}
